package com.lt.bcra.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lt.bcra.entity.BcraCategory;
import com.lt.bcra.entity.BcraDictionary;
import com.lt.bcra.exception.BaseException;
import com.lt.bcra.mapper.BcraDictionaryMapper;
import com.lt.bcra.result.ResponseEnum;
import com.lt.bcra.result.ResultData;
import com.lt.bcra.service.BcraDictionaryService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LuoTian
 * @since 2022-05-30
 */
@Service
public class BcraDictionaryServiceImpl extends ServiceImpl<BcraDictionaryMapper, BcraDictionary> implements BcraDictionaryService {

    @Autowired
    BcraDictionaryMapper bcraDictionaryMapper;

    @Override
    public ResultData listByCategoryId(Integer categoryId,Long current,Long size) {
        QueryWrapper<BcraDictionary> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("category_id",categoryId);

        Page<BcraDictionary> pageParam = new Page<>(current, size);

        bcraDictionaryMapper.selectPage(pageParam,queryWrapper);

        List<BcraDictionary> records = pageParam.getRecords();//当前页存在记录
        long total = pageParam.getTotal();//总条数
        long current1 = pageParam.getCurrent();//当前页码
        long pages = pageParam.getPages();//一共页数
        long size1 = pageParam.getSize();//每页条数

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("records", records);
        map.put("total", total);
        map.put("current", current1);
        map.put("pages", pages);
        map.put("size", size1);

        return ResultData.getResult(map);
    }

    @Override
    public ResultData saveDictionary(BcraDictionary bcraDictionary) {
        String dictionary = bcraDictionary.getDictionary();
        String code = bcraDictionary.getCode();

        QueryWrapper<BcraDictionary> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("dictionary", dictionary);
        if (bcraDictionaryMapper.selectOne(queryWrapper)!=null){
            throw new BaseException(ResponseEnum.DICTIONART_SAME_ERROR);
        }

        QueryWrapper<BcraDictionary> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("code", code);
        if (bcraDictionaryMapper.selectOne(queryWrapper1)!=null){
            throw new BaseException(ResponseEnum.CODE_SAME_ERROR);
        }

        int insert = bcraDictionaryMapper.insert(bcraDictionary);
        return ResultData.getResult(insert);
    }
}
